<!-- 试题 -->
<script lang="ts">
export declare interface OptionsType {
  isAnswer: number;
  optionId: string;
  optionText: string;
}
export declare interface QuestionType {
  questionId: string;
  analysisText: string;
  type: number;
  _title?: string;
  stemText: string;
  subjectTitle?: string;
  options: Array<OptionsType>
}
export declare interface UseConditionInfoType {
  answerCount: string;
  correctCount: string;
  rate?: number;
  refPaper: Array<{
    isEnabled: number;
    poolCode: string;
    title: string;
    branchName: string;
  }>
  refPool: Array<{
    isEnabled: number;
    paperCode: string;
    title: string;
    branchName: string;
  }>
}
</script>
<script setup lang='ts'>
import { onMounted, reactive, ref } from 'vue'
import { form, params, dictionary, tableKeyList, batchBtnList } from './conf'
import { useCurrentInstance } from '@/common/utils/methods'
import { ResponseType, } from '@/common/types/response';
import batchUploadVue, { SubjectType } from './component/batchUpload.vue';
import questionSheetVue, { ruleFormType } from './component/questionSheet.vue';

const { $confirm, $message, $axios, branchId, brandId, branchType } = useCurrentInstance();
const data = reactive({
  getData: false,
  totalNum: 0,
  list: [],
  params,
  activeQuestion: {} as QuestionType,
  previewDialog: false,
  useConditionDialog: false,
  useConditionInfo: {} as UseConditionInfoType,
  subjectList: [] as Array<SubjectType>,
  sheetType: '', // 试题编辑弹窗类型
  currentData: {}, // 当前正在编辑的试题信息
})

const questionPreview = (question: QuestionType) => { // 试题预览
  data.activeQuestion = {
    ...question,
    _title: ['单选', '多选', '判断', '填空'][question.type - 1] + '题'
  };
  data.previewDialog = true;
}

const questionAction = (question: QuestionType, status: number) => { // 试题操作：启禁用、公开、删除
  const tipMap = { '0': '禁用', '1': '启用', '2': '公开', '-1': '删除' }
  $confirm(
    `<p>确定${tipMap[status]}试题么？</p><p class="_tip _required">操作后此试题在题库中将被自动${tipMap[status]}。</p>`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      dangerouslyUseHTMLString: true,
      type: 'warning'
    }
  ).then(() => {
    $axios.post('/training.exam.api/question/enableOrDelete', {
      branchId,
      brandId,
      questionIds: [question.questionId],
      status
    }).then((res: ResponseType) => {
      if (res.code === '200') {
        data.getData = true;
        $message.success('操作成功')
      } else {
        $message.success(res.msg || '操作失败');
      }
    })
  })
}

const showUseCondition = (question: QuestionType) => { // 获取试题使用情况
  data.activeQuestion = question;
  $axios.post('/training.exam.api/question/overview', {
    branchId, brandId,
    questionId: question.questionId
  }).then((res: ResponseType) => {
    if (res.code === '200') {
      const { correctCount, answerCount } = res.data;
      const rate = Number(answerCount) ? ((Number(correctCount) / Number(answerCount)) * 100).toFixed(2) : 0;
      data.useConditionInfo = { ...res.data, rate }
      data.useConditionDialog = true;
    } else {
      $message.error(res.msg)
    }
  })
}

const batchConfirm = (val: Array<QuestionType>, status: number) => {
  const questionIds = val.map((item: QuestionType) => item.questionId)
  $axios.post('/training.exam.api/question/enableOrDelete', {
    branchId,
    brandId,
    questionIds,
    status
  }).then((res: ResponseType) => {
    if (res.succeed) {
      $message.success('操作成功')
      data.getData = true
    } else {
      $message.error(res.msg)
    }
  })
}

// 上传弹窗节点
const batchUpload = ref();
const showUpload = () => {
  batchUpload.value.showUploadDialog();
}

// 新增或编辑试题
const questionSheet = ref();
const questionSheetAction = (actionType: string, data: SubjectType) => {
  if (actionType === 'add' && [1, 2].includes(data.type)) {
    data.analysisText = '';
    data.stemText = '';
    data.opsType = 1; // 添加
    data.options = [{
      optionId: '',
      optionText: '',
      isAnswer: 0,
      answerText: ''
    }]
  } else {
    data.opsType = 2; // 编辑
  }
  
  questionSheet.value.setQuestionInfo({
    ...data,
    _actionType: actionType,
    _type: data.type
  })
}

// 试题 新增/编辑 预览
const showPreviewDialog = (previewInfo: ruleFormType) => {
  const { analysisText, stemText, subjectId, options, type } = previewInfo;
  const currentSubject = data.subjectList.filter((item: SubjectType) => (item.value === subjectId));
  questionPreview({
    questionId: '',
    analysisText,
    type,
    stemText,
    subjectTitle: currentSubject[0].title,
    options
  })
}


onMounted(() => {
  $axios.post('/training.exam.api/subject/list', { branchId, brandId, pageSize: 1000 }).then((res: ResponseType) => {
    data.subjectList = res.data.list.map((subject: SubjectType) => {
      return { value: subject.subjectId, label: subject.title }
    })
  })
})


</script>

<template>
  <div>
    <ConditionView
      v-model:params="data.params"
      :form="form"
      :dictionary="{ ...dictionary, subjectId: data.subjectList }"
      @search="data.getData = true"
    ></ConditionView>

    <ListView
      :tableKeyList="tableKeyList"
      :list="data.list"
      :dictionary="{ ...dictionary, subjectId: data.subjectList }"
      fixed="right"
      :hasHandle="true"
      :totalNum="data.totalNum"
      :batchBtnList="batchBtnList"
      @batchConfirm="batchConfirm"
    >
      <template #rightBtn>
        <el-button type="primary" @click="questionSheetAction('add', { type: 1 })">
          <el-icon>
            <plus />
          </el-icon>单选
        </el-button>
        <el-button type="primary" @click="questionSheetAction('add', { type: 2 })">
          <el-icon>
            <plus />
          </el-icon>多选
        </el-button>
        <el-button type="primary" @click="questionSheetAction('add', { type: 3 })">
          <el-icon>
            <plus />
          </el-icon>判断
        </el-button>
        <el-button type="primary" @click="showUpload">导入</el-button>
      </template>
      <template #handle="{ row }">
        <el-button size="small" @click="questionPreview(row)">预览</el-button>
        <el-button
          size="small"
          v-if="row.isEnabled == 0"
          :disabled="row.ownerType === 2 && branchType === 1"
          @click="questionAction(row, 1)"
        >启用</el-button>
        <el-button
          size="small"
          v-if="row.isEnabled == 1"
          :disabled="row.ownerType === 2 && branchType === 1"
          @click="questionAction(row, 0)"
        >禁用</el-button>
        <el-button
          size="small"
          :disabled="row.ownerType === 2 && branchType === 1"
          @click="questionSheetAction('edit', row)"
        >编辑</el-button>
        <el-button
          size="small"
          :disabled="row.isEnabled === 1 || row.ownerType === 2 && branchType === 1"
          @click="questionAction(row, -1)"
        >删除</el-button>
        <el-button
          size="small"
          v-if="branchType === 1 && row.visable == 0"
          @click="questionAction(row, 2)"
        >公开</el-button>
        <el-button size="small" type="primary" @click="showUseCondition(row)">使用情况</el-button>
      </template>
    </ListView>
    <Pagination
      url="/training.exam.api/question/list"
      v-model:list="data.list"
      v-model:getData="data.getData"
      :params="data.params"
      :autoLoad="true"
      @setTotalNum="(num: number) => (data.totalNum = num)"
    ></Pagination>

    <!-- 预览弹窗 -->
    <el-dialog v-model="data.previewDialog" width="600px" :title="data.activeQuestion._title">
      <p class="title">科目名称：{{ data.activeQuestion.subjectTitle }}</p>
      <p class="remark">题干：{{ data.activeQuestion.stemText }}</p>
      <p>选项：</p>
      <div
        class="option"
        v-for="(option, i) in data.activeQuestion.options || []"
        :key="option.optionId"
        :class="option.isAnswer == 1 ? 'right' : 'error'"
      >
        <span
          v-if="[1, 2].includes(data.activeQuestion.type)"
        >{{ String.fromCharCode(64 + Number(i + 1)) + ' ' + option.optionText }}</span>
        <span v-if="data.activeQuestion.type === 3">{{ option.optionText }}</span>
      </div>
      <p class="title s2">解析：</p>
      <p class="remark">{{ data.activeQuestion.analysisText || '暂无解析' }}</p>
    </el-dialog>

    <!-- 使用情况弹窗 -->
    <el-dialog v-model="data.useConditionDialog" title="使用情况" width="1280px">
      <el-row>
        <el-col :span="8">
          答题次数：
          <strong>{{ data.useConditionInfo.answerCount }}</strong>
        </el-col>
        <el-col :span="8">
          正答次数：
          <strong>{{ data.useConditionInfo.correctCount }}</strong>
        </el-col>
        <el-col :span="8">
          正答率：
          <strong>{{ data.useConditionInfo.rate }}%</strong>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row :gutter="20" class="_mt20">
        <el-col :span="12">
          <p style="margin-bottom:10px">
            已被
            <strong>{{ data.useConditionInfo.refPool.length }}</strong> 个题库使用
          </p>
          <el-table :data="data.useConditionInfo.refPool" border style="width: 100%">
            <el-table-column prop="poolCode" label="ID" width="150" />
            <el-table-column prop="title" label="题库" />
            <el-table-column prop="isEnabled" label="状态">
              <template #default="{ row }">{{ row.isEnabled === 1 ? '启用' : '禁用' }}</template>
            </el-table-column>
            <el-table-column prop="branchName" label="归属" v-if="branchType === 1" />
          </el-table>
        </el-col>
        <el-col :span="12">
          <p style="margin-bottom:10px">
            已被
            <strong>{{ data.useConditionInfo.refPool.length }}</strong> 个试卷使用
          </p>
          <el-table :data="data.useConditionInfo.refPaper" border style="width: 100%">
            <el-table-column prop="paperCode" label="ID" width="150" />
            <el-table-column prop="title" label="试卷" />
            <el-table-column prop="isEnabled" label="状态">
              <template #default="{ row }">{{ row.isEnabled === 1 ? '启用' : '禁用' }}</template>
            </el-table-column>
            <el-table-column prop="branchName" label="归属" v-if="branchType === 1" />
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 导入弹窗 -->
    <batchUploadVue :subjectList="data.subjectList" ref="batchUpload" />

    <!-- 试题弹窗 -->
    <questionSheetVue
      :subjectList="data.subjectList"
      ref="questionSheet"
      @updateList="data.getData = true"
      @preview="showPreviewDialog"
    />
  </div>
</template>

<style scoped>
.title {
  font-size: 14px;
  color: #333;
  margin-bottom: 20px;
  line-height: 30px;
}
.remark {
  color: #4d4d4d;
  line-height: 20px;
  padding-bottom: 10px;
}
.option {
  line-height: 20px;
  background: rgba(#3d88f2, 0.1);
  color: #3d88f2;
  padding: 8px 16px;
  border-radius: 4px;
  margin: 10px 0;
}
.option.right {
  background: #3d88f2;
  color: #fff;
}
.option.error {
  background: #ff5a6d;
  color: #fff;
}
</style>